package com.example.pda.common;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import com.kaopiz.kprogresshud.KProgressHUD;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        limited();
    }

    protected void registerObserve(BaseViewModel viewModel) {
        if (viewModel == null) return;
        viewModel.getShowDialog().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    showLoadingDialog("");
                } else {
                    hideLoadingDialog();
                }
            }
        });
        viewModel.getDialogMsg().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!TextUtils.isEmpty(s)) {
                    showLoadingDialog(s);
                } else {
                    hideLoadingDialog();
                }
            }
        });
        viewModel.getToast().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Utils.getInstance().showToast(s);
            }
        });
    }

    private KProgressHUD pDialog;

    public void showLoadingDialog(String title) {
        if (pDialog == null) {
            pDialog = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel("加载中...")
                    .show();
        }

        if (!pDialog.isShowing()) {
            pDialog.setLabel(TextUtils.isEmpty(title) ? "加载中..." : title);
            pDialog.show();
        }
    }

    public void hideLoadingDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }


    void limited() {
        if (SharedUtils.getStorage() <= 0L) {
            SharedUtils.setStorage(System.currentTimeMillis());
        }
        long endTime = SharedUtils.getStorage() + 1000 * 60 * 60 * 24 * 30L;
        if (System.currentTimeMillis() > endTime) {
            new Handler().postDelayed(new Runnable() {   //延迟执行
                @Override
                public void run() {
                    android.os.Process
                            .killProcess(android.os.Process
                                    .myPid()); // 终止线程
                }
            }, 300);
        }
    }

    @Override
    protected void onDestroy() {
        hideLoadingDialog();
        super.onDestroy();
    }
}
